<?php
App::uses('Sanitize', 'Utility');
class ArticlesController extends AppController {
	public $name = 'Articles';
	public $components = array('Session', 'Security', 'Auth');
	//public $helpers = array('Cache');
	public $paginate = array(
            'fields' => array('User.username', 'user_id', 'id', 'title', 'body', 'created', 'modified', 'comment_count', 'id'),
            'limit' => 50,
            'order' => array('id' => 'DESC')
    );

	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('view', 'viewArticles');
		$this->Auth->authorize = 'controller';

	}

	public function isAuthorized($user) {
		if ($this->action === 'add') {
			// All registered users can add posts
			return true;
		}
		if (in_array($this->action, array('edit'))) {
			$articleId = $this->request->params['pass'][0];

			return $this->Article->isOwnedBy($articleId, $user['id'], $user['Role']['access']);
		}
		return true;
	}

	public function index(){
		$this->set('articles', $this->paginate('Article'));
	}

	public function add(){
		$this->loadModel('Category');

		$this->set("categories", $this->Category->find('list'));
		$this->set("selectedCategories", null);
		if($this->request->is('post')){
			$this->Article->create();
			if($this->Article->saveAssociated($this->request->data)){
				$this->Session->setFlash("Your article has been added. ID: " . $this->Article->id, "default", array('class' => 'success'));
				$this->redirect(array("action" => "index"));
			}
		}
	}

	public function edit($id = null){
		$this->Article->id = $id;
		if(!$this->Article->exists()){
			throw new NotFoundException("Article not found");
		}
		$this->loadModel('Category');
		$selectedCategories = null;
		if($this->request->is('get')){
			$this->request->data = $this->Article->read();

			$this->set(array(
				"categories" => $this->Category->find('list'),
				"selectedCategories" => $selectedCategories
			));
		}else{
			if($this->Article->saveAssociated($this->request->data)){

				$this->Session->setFlash("Article updated", "default", array("class" => "success"));
				$this->redirect(array("action" => "index"));
			}
		}
	}



	public function viewArticles(){
		// default method
		$this->layout = 'home';

		$this->set('articles', $this->Article->find('all', array(
			'fields' => array('User.username', 'Article.title', 'Article.body', 'Article.created', 'Article.id', 'Article.comment_count'),
			'order' => array('id' => 'DESC')
		)));
	}

	public function view($id){
		$this->Article->id = $id;
		if(!$this->Article->exists()){
			$this->redirect("/");
		}

		$this->layout = 'home';
		$this->set('article', $this->Article->read());

		if($this->request->is("post")){
			$this->loadModel('Comment');
			$this->Comment->create();
			$this->request->data('Comment.ip', $_SERVER['REMOTE_ADDR']);
			if($this->Comment->save($this->request->data)){
				$this->Session->setFlash("Your comment has been added", "default", array("class" => "success"));
				$this->redirect($this->referer());
			}
		}

	}

	public function delete(){
		if($this->request->is("get")){
			throw new MethodNotAllowedException();
		}elseif($this->request->is("post")){
			$i = 0;
			foreach($this->request->data['Article']['selectedArticles'] AS $articleId){
				// delete article
				if($this->Article->isOwnedBy($articleId, $this->Auth->User('id'), $_SESSION['Auth']['User']['Role']['access'])){
					$this->Article->id = $articleId;
					$this->Article->delete();
					$i++;
				}
			}
			$this->Session->setFlash($i . ": Articles have been deleted.", "default", array('class' => 'error-message'));
			$this->redirect(array("action" => "index"));
		}
	}
}